package com.swh.controller;

import com.alibaba.fastjson.JSONObject;
import com.swh.entity.User;
import com.swh.servic.UserServic;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/11/26 16:42
 * @Version: 1.0
 */
@WebServlet("/wx_login")
public class WxLoginServlet extends HttpServlet {
    private UserServic userService = new UserServic();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Properties prop = new Properties();
        prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));

        String appid = prop.getProperty("wx.AppID");

        String appSecret = prop.getProperty("wx.AppSecret");

        String code = request.getParameter("code");

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appid +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        // 根据code请求access_toekn
        HashMap<String, String> auth = execute(url);

        String access_token = auth.get("access_token");

        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                access_token + "&openid=" + auth.get("openid}");

        HashMap<String, Object> userInfo = execute(url);

        User user = userService.findByWxOpenId(auth.get("openid"));

        if (user == null) {
            //第一次微信登录
            user = new User();

            //获取微信头像
            user.setPic(userInfo.get("headimgurl").toString());

            // 随机用户名(11位随机字符串)
//            user.setUsername(UUID.randomUUID().toString().substring(36 - 15));

            // 性别
            user.setGender(userInfo.get("sex").toString());

            // 用户的昵称
            user.setRealName(userInfo.get("nickname").toString());

            // 查询最大id值
            Long maxId = userService.findMaxId();
            user.setId(maxId + 1);

            // 注册一个新的用户
            userService.save(user);

        }

        request.getSession().setAttribute("login", user);

        response.sendRedirect("/html/home.jsp");
    }

    public HashMap execute(String url) {
        try {
            CloseableHttpClient client = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = client.execute(httpGet);

            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(entity, "UTF-8");

            return JSONObject.parseObject(jsonStr, HashMap.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
